<template>
  <div class="book-detail">

    <div class="book-cover">
      <img :src="book.cover" alt="Book Cover" />
    </div>

    <div class="book-info">
      <h1 class="book-title">{{ book.title }}</h1>
      <span class="author" @click="goToAuthorDetail(book.author)">{{ book.author }}</span>
      <span class="publisher" @click="goToPublisher(book.publisher)">{{book.publisher}}</span>
      <p class="publish-date">出版时间: <span>{{ book.publishDate }}</span></p>
      <p class="page-count">页数: <span>{{ book.pageCount }}</span>页</p>
      <p class="price">定价: <span>{{ book.price }}</span>元</p>
      <p class="isbn" v-if="book.isbn">ISBN: <span>{{ book.isbn }}</span></p>
    </div>

    <div class="rating">
      <p class="rating-label">评分：</p>
      <div class="rating-details">
        <div class="rating-number">
          <span class="rating-value">{{ book.rating }}</span>
        </div>
        <div class="rating-stars-count">
          <!-- 星星评价 -->
          <el-rate
              v-model="book.rating"
              disabled
              text-color="#ff9900"
          />
          <!-- 评价人数 -->
          <p class="rating-count">{{ book.ratingCount }}人评价</p>
        </div>
      </div>
    </div>

    <div class="info">
      <p class="summary">内容简介：{{ book.summary }}</p>
      <p class="author-intro">作者简介：{{ book.authorIntro }}</p>
    </div>

    <div class="separator"></div>

    <div class="recommendation" v-if="recommendedBooks.length">
      <h2 class="book-like">喜欢{{ book.title }}的人也喜欢:</h2>
      <div class="book-grid">
        <div v-for="book in recommendedBooks" :key="book.id" class="book-card">
          <router-link
              :key="book.id"
              :to="{
                name: 'BookDetail',
                params: { bookType: book.bookType },
                query: { id: book.id }
              }"
              class="book-link"
          >
            <img :src="book.cover" alt="Book Cover" class="book-cover">
            <h3 class="book-title">{{ book.title }}</h3>
          </router-link>
          <h4 class="book-author">作者: {{ book.author }}</h4>
        </div>
      </div>
    </div>


  </div>
</template>

<script>
import { books } from '@/assets/data/booksData';
import {authors} from "@/assets/data/authorsData";
import '@/assets/css/BookDetail.css'

export default {
  name: 'BookDetail',
  props: ['tag'],
  data() {
    return {
      book: {},
      books: books, // 初始化 books 数组
      author: {},
      authors: authors, // 初始化 authors 数组
    };
  },
  computed: {
    filteredBooks() {
      // 筛选出标签包含当前标签的书籍
      return this.books.filter(book => book.tags.includes(this.tag));
    },
    // 筛选出与当前书籍具有相同标签的书籍，并随机选择8本
    recommendedBooks() {
      if (!this.book || !this.book.tags) return [];

      const matchedBooks = this.books.filter(book =>
          book.id !== this.book.id &&
          book.tags.some(tag => this.book.tags.includes(tag))
      );

      // 随机排序matchedBooks数组
      for (let i = matchedBooks.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [matchedBooks[i], matchedBooks[j]] = [matchedBooks[j], matchedBooks[i]];
      }
      // 返回随机的8本书籍
      return matchedBooks.slice(0, 8);
    },
  },
  created() {
    this.fetchBookDetails();
  },
  watch: {
    // 监听路由变化，重新获取书籍详情
    '$route'(to, from) {
      this.fetchBookDetails();
    }
  },
  methods: {
    fetchBookDetails() {
      const bookId = this.$route.query.id;

      if (!bookId) {
        this.$router.replace({ name: 'Home' });
        return;
      }

      this.book = this.books.find(book => book.id.toString() === bookId.toString());
      if (this.book) {
        // 确保计算属性可以基于当前书籍重新计算
        this.$nextTick(() => {
          console.log('无效的数据:', this.recommendedBooks);
        });
      } else {
        this.$router.replace({ name: 'Home' });
      }
    },
    goToAuthorDetail(authorName) {
      // 现在 authorName 是一个字符串，直接使用它生成跳转路径
      if (typeof authorName !== 'string') {
        console.error('');
        return;
      }
      this.$router.push({ path: `/authordetail/${authorName}` });
    },
    goToPublisher(publisher) {
      // 现在 authorName 是一个字符串，直接使用它生成跳转路径
      if (typeof publisher !== 'string') {
        console.error('无效的数据');
        return;
      }
      this.$router.push({ path: `/publisherbooklist/${publisher}` });
    },
  },
};
</script>
